package com.neouton.crm.customer.service.impl;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.entity.FeeMainVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.customer.entity.ContactsVO;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.customer.entity.CustomerVO;
import com.neouton.crm.customer.mapper.CustomerMapper;
import com.neouton.crm.customer.service.CustomerService;
import com.neouton.crm.enterprise.entity.EnterpriseVO;
import com.neouton.crm.enterprise.mapper.EnterpriseMapper;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.op.entity.SalesOpportunityVO;
import com.neouton.crm.op.mapper.SalesOpportunityMapper;
import com.neouton.crm.pm.entity.BackMoneyPlanVo;
import com.neouton.crm.pm.entity.BackMoneyRecordVo;
import com.neouton.crm.pm.entity.ContractInfoVO;
import com.neouton.crm.pm.entity.SalesProjectManageVO;
import com.neouton.crm.pm.mapper.BrAndBmrMapper;
import com.neouton.crm.pm.mapper.ContractInfoMapper;
import com.neouton.crm.pm.mapper.SalesProjectManageMapper;
import com.neouton.crm.pm.service.BrAndBmrService;
import com.neouton.crm.transpondEmail.entity.TranspondEmailVO;
import com.neouton.crm.transpondEmail.mapper.TranspondEmailMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.ReimburseService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerMapper customerMapper;

    @Resource
    private IDictionaryService dictionaryService;

    @Resource
    private FeginService feginService;

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private IApprovalService approvalService;

    @Resource
    private TranspondEmailMapper transpondEmailMapper;

    @Value("${webSit.web}")
    private String webSitUrl;
    /**
     * 多条件分页查询客户信息列表
     * @Timestamp: 2022-11-18
     * @Author: WuJie
     * @param page 分页信息
     * @param customer 其余查询条件
     * @return 分页查询结果
     */
    @Override
    public PageUtil<CustomerVO> queryCustomerByPage(IPage page, CustomerVO customer,String orderBy,String token){
        IPage<CustomerVO> iPage;
        //获取当前登录用户信息
        SysUserEntity userInfo = feginService.searchUserInfoById(AuthUtils.getUserId(), token).getResult();

        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode("customer");
        Boolean result = false;
        if (!authUserIList.isEmpty()){
            for (SysUserEntity item:authUserIList){
                if (Objects.equals(item.getUserId(), AuthUtils.getUserId())){
                    result = true;
                    break;
                }
            }
        }
        List<SysUserEntity> allUserInfo = new ArrayList<>();
        if (result){
            iPage = customerMapper.queryCustomerByPage(page,customer,orderBy,null);
        }else {
            //判断是否领导
            if (userInfo.getIsLeader() == 1) {
                allUserInfo = feginService.recursiveQueryAllUserByLeaderId(AuthUtils.getUserId(), token).getResult();
            }
            allUserInfo.add(userInfo);

            iPage = customerMapper.queryCustomerByPage(page, customer, orderBy, allUserInfo);
        }

        List<ContactsVO> contactsInfo = customerMapper.queryAllContacts();
        List<CustomerVO> records = iPage.getRecords();
        for (int i = 0; i < records.size(); i++) {
            List<ContactsVO> con = new ArrayList<>();
            for (int j = 0; j < contactsInfo.size(); j++) {
                if (records.get(i).getCustomerId().equals(contactsInfo.get(j).getCustomerId())){
                    con.add(contactsInfo.get(j));
                }
            }
            if (null != con && con.size() != 0){
                records.get(i).setContacts(con);
            }
        }

        return new PageUtil(iPage);
    }


    /**
     * 获取客户待办列表
     * @param page
     * @param customer
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<CustomerVO> getCustomerToDoList(IPage page, CustomerVO customer,String orderBy,String token){
        //1.调取工作流
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else {
            IPage<CustomerVO> iPage = customerMapper.getCustomerToDoList(page, customer, orderBy, activitiVOS);
            List<CustomerVO> records = iPage.getRecords();
            List<ContactsVO> contactsInfo = customerMapper.queryAllContacts();
            for (int i = 0; i < records.size(); i++) {
                List<ContactsVO> con = new ArrayList<>();
                for (int j = 0; j < contactsInfo.size(); j++) {
                    if (records.get(i).getCustomerId().equals(contactsInfo.get(j).getCustomerId())){
                        con.add(contactsInfo.get(j));
                    }
                }
                if (null != con && con.size() != 0){
                    records.get(i).setContacts(con);
                }
            }


            return new PageUtil(iPage);
        }
    }


    /**
     * 获取客户已办列表
     * @param page
     * @param customer
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<CustomerVO> getCustomerDoneList(IPage page, CustomerVO customer,String orderBy,String token){
        IPage<CustomerVO> iPage = customerMapper.getCustomerDoneList(page, customer, orderBy);
        List<CustomerVO> records = iPage.getRecords();
        List<ContactsVO> contactsInfo = customerMapper.queryAllContacts();
        for (int i = 0; i < records.size(); i++) {
            List<ContactsVO> con = new ArrayList<>();
            for (int j = 0; j < contactsInfo.size(); j++) {
                if (records.get(i).getCustomerId().equals(contactsInfo.get(j).getCustomerId())){
                    con.add(contactsInfo.get(j));
                }
            }
            if (null != con && con.size() != 0){
                records.get(i).setContacts(con);
            }
        }
        return new PageUtil(iPage);
    }


    /**
     * 获取客户申请记录列表
     * @param page
     * @param customer
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<CustomerVO> getCustomerRecordsList(IPage page, CustomerVO customer,String orderBy,String token){
        Integer userId = AuthUtils.getUserId();
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode("approvalRecord");
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }
        IPage<CustomerVO> iPage = customerMapper.getCustomerRecordsList(page, customer, orderBy, userList);
        List<CustomerVO> records = iPage.getRecords();
        List<ContactsVO> contactsInfo = customerMapper.queryAllContacts();
        for (int i = 0; i < records.size(); i++) {
            List<ContactsVO> con = new ArrayList<>();
            for (int j = 0; j < contactsInfo.size(); j++) {
                if (records.get(i).getCustomerId().equals(contactsInfo.get(j).getCustomerId())){
                    con.add(contactsInfo.get(j));
                }
            }
            if (null != con && con.size() != 0){
                records.get(i).setContacts(con);
            }
        }
        return new PageUtil(iPage);
    }

    /**
     * 新增或更新客户信息
     * @Timestamp: 2022-11-17
     * @Author: WuJie
     * @param customer 需更新实体
     * @return 成功失败
     */
    @Transactional
    public Boolean saveOrUpdateCustomer(CustomerVO customer,String token) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("客户关系管理审批流程");
        activitiVO.setProcessCode("customer_approval");
        activitiVO.setNextNodeParams(Constants.LEADER_KEY);
        //商务信息
        SysUserEntity businessAffairs = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
        activitiVO.setNextNodeAssignee(businessAffairs.getAccount());

        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);
        customer.setBusinessId(responseAPI.getResult().getBusinessId());
        ApprovalVO approval = approvalService.initApprovalAndLog(responseAPI.getResult().getBusinessId(),
                Constants.CUSTOMER_TASK_TYPE, customer.getReason(), "",businessAffairs.getUserId(),"");
        customer.setApprovalId(approval.getApprovalId());

        boolean data;

        customer.setIsDelete(Constants.CUSTOMER_STOP);
        customer.setIsSupplier(Constants.CUSTOMER_NOT_SUPPLIER);
        Integer userId = AuthUtils.getUserId();
        //去除联系人为空的集合
        List<ContactsVO> contactsVO = new ArrayList<>();
        for (int i = 0; i < customer.getContacts().size(); i++) {
            if (customer.getContacts().get(i).getContacts() != null || customer.getContacts().get(i).getPhoneNumber() != null || customer.getContacts().get(i).getPhoneNumber() != null){
                contactsVO.add(customer.getContacts().get(i));
            }
        }



        if (null == customer.getCustomerId()) {
            customer.setCreator(userId);
            customer.setLastUpdateBy(userId);
            customer.setPossessor(userId);
            data = customerMapper.insertCustomer(customer);
            if (data && contactsVO.size() != 0){
                Integer id = customer.getCustomerId();
                for (ContactsVO item : contactsVO) {
                    item.setCustomerId(id);
                    item.setApprovalId(approval.getApprovalId());
                }
                data = customerMapper.insertContacts(contactsVO);
            }
        } else {
            customerMapper.backCustomerData(customer);
            customerMapper.backContactsData(customer);
            customer.setLastUpdateBy(userId);
            customer.setAuditOpinion(null);
            data = customerMapper.updateCustomer(customer);
            if (data && contactsVO.size() != 0){
                Integer id = customer.getCustomerId();
                for (ContactsVO item : contactsVO) {
                    item.setCustomerId(id);
                    item.setApprovalId(approval.getApprovalId());
                }
                customerMapper.deleteContacts(id);
                data = customerMapper.updateContacts(contactsVO);
            }
        }

        // 转发人记录
        if (customer.getTranspondUseIdList() != null && customer.getTranspondUseIdList().size() > 0){
            TranspondEmailVO transpondEmailVO = new TranspondEmailVO();
            transpondEmailVO.setApprovalId(customer.getApprovalId());
            transpondEmailVO.setTranspondUseIdList(customer.getTranspondUseIdList());
            transpondEmailMapper.insertTranspondEmailInfo(transpondEmailVO);
        }

        if (businessAffairs.getUserId().equals(AuthUtils.getUserId())){
            //跳过第一步审批
            this.approveCustomer(customer,token, true);
        }else{
            sendEmailAndPushNotice(businessAffairs,customer,token);
        }
        return data;
    }

    /**
     * 禁用
     * @param customerId
     * @return
     */
    @Override
    public Boolean deleteCustomerById(Integer customerId){
        //获取当前登录人ID
        Integer userId = AuthUtils.getUserId();
        Integer isDelete = Constants.CUSTOMER_STOP;
        Boolean data = customerMapper.updateIsDelete(customerId,userId,isDelete);
        return data;
    }

    /**
     * 禁用
     * @param approvalId crm审批日志id
     * @return
     */
    @Override
    public Boolean forbiddenCustomerByApplyId(Integer approvalId){
        //获取当前登录人ID
        Integer userId = AuthUtils.getUserId();
        Integer isDelete = Constants.CUSTOMER_STOP;
        Boolean data = customerMapper.forbiddenCustomerByApplyId(approvalId,userId,isDelete);
        return data;
    }


    /**
     * 启用
     * @param customerId
     * @param backUserId
     * @return
     */
    @Override
    public Boolean enableCustomerById(Integer customerId,Integer backUserId){
        Integer isDlete = Constants.CUSTOMER_START;
        Boolean data = customerMapper.updateIsDelete(customerId, backUserId,isDlete);
        return data;
    }

    /**
     * 根据部分条件查询客户信息是否存在
     * @param customer
     * @return
     */
    @Override
    public CustomerVO queryCustomerExit(CustomerVO customer){
        return customerMapper.queryCustomerExit(customer);
    }

    /**
     * 审批通过
     * @param customer
     * @return 成功失败
     */
    @Transactional
    public Boolean approveCustomer(CustomerVO customer,String token,Boolean auto) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(customer.getBusinessId());
        //获取当前所处节点
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);

//        workFlowFeginService.approvalProcessByBusinessId(activitiVO);
        //总经理信息
//        SysUserEntity generalManager = dictionaryService.queryMenuUserIdsByCode("president").get(0);
        //商务信息
//        SysUserEntity businessAffairs = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
        //记录审批日志
        if(auto){
            approvalService.insertApprovalLog(customer.getApprovalId(),"通过",
                    "系统判定跳过",customer.getAuditOpinion());
        }else {
            //记录日志
            approvalService.insertApprovalLog(customer.getApprovalId(),"通过",
                    "",customer.getAuditOpinion());
        }
        if ("商务".equals(processNodeNameAndCode.getResult().getName())){
            // 审批通过
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);

            customerMapper.updateIsDelete(customer.getCustomerId(),null,Constants.CUSTOMER_START);
            approvalService.approved(null, customer.getApprovalId());
            apSendEmailAndPushNotice(customer,token);
        }
//        else{
//            //总经理信息
//            SysUserEntity generalManager = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//            activitiVO.getCustomParams().put("afterSales",generalManager.getAccount());
//
//            //审批通过（使用动态入参传入下一审批人）
//            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
//            //获取下一节点
//            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
//            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){ //记录日志
//                this.approveCustomer(customer,token,true);
//            }else {
//                approvalService.updateNextApproverByApprovalId(generalManager.getUserId(), customer.getApprovalId());
//                sendEmailAndPushNotice(generalManager,customer,token);
//            }
//        }
        return true;
    }
    /**
     * 审批驳回
     * @param customer
     * @return
     */
    @Transactional
    public Boolean rejectionCustomer(CustomerVO customer,String token) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(customer.getBusinessId());
        // 删除实例，驳回至起点
        workFlowFeginService.deleteInstance(activitiVO);
        rjSendEmailAndPushNotice(customer, token);
        approvalService.insertApprovalLog(customer.getApprovalId(), "驳回",
                "", customer.getAuditOpinion());
        return approvalService.approvalRejection(null, customer.getApprovalId());
    }
    /**
     * 查询并更改是否为供应商，每次刷新更新
     * @return true成功，false失败
     */
    @Override
    public Boolean selectIsSupplier(){
        Boolean flage = customerMapper.updateIsSupplier();
        return flage;
    }

    @Override
    public List<CustomerVO> selectCustomerByEnterpriseId(CustomerVO customer,List<SysUserEntity> userList) {
        return customerMapper.selectCustomerByEnterpriseId(customer,userList);
    }


    @Override
    public List<CustomerVO> selectAllCustomers(){
        return customerMapper.selectAllCustomers();
    }

    @Override
    public CustomerVO queryCustomerById(Integer customerId) {
        return customerMapper.queryCustomerById(customerId);
    }

    @Override
    public List<CustomerVO> selectCustomerByCustomerName(String customerName) {
        return customerMapper.selectCustomerByName(customerName);
    }

    @Override
    public CustomerVO queryCustomerApprovalByWorkId(Integer workId){
        return customerMapper.queryCustomerApprovalByWorkId(workId);
    }

    @Override
    public List<CustomerVO> selectAllEnterprise() {
        return customerMapper.selectAllEnterprise();
    }


    @Override
    public void exportCustomerInfo(HttpServletResponse response, CustomerVO customer, String token) throws Exception {
        //获取当前登录用户信息
        SysUserEntity userInfo = feginService.searchUserInfoById(AuthUtils.getUserId(), token).getResult();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode("customer");
        Boolean result = false;
        if (!authUserIList.isEmpty()){
            for (SysUserEntity item:authUserIList){
                if (Objects.equals(item.getUserId(), AuthUtils.getUserId())){
                    result = true;
                    break;
                }
            }
        }
        List<CustomerVO> cusotmerList = new ArrayList<>();
        List<SysUserEntity> allUserInfo = new ArrayList<>();
        if (result){
            cusotmerList = customerMapper.queryAllCusotmer(customer,null);
        }else {
            //判断是否领导
            if (userInfo.getIsLeader() == 1) {
                allUserInfo = feginService.recursiveQueryAllUserByLeaderId(AuthUtils.getUserId(), token).getResult();
            }
            allUserInfo.add(userInfo);
            cusotmerList = customerMapper.queryAllCusotmer(customer, allUserInfo);
        }
        List<String> codes = new ArrayList<>();
        codes.add("rank_correlation");
        codes.add("isSupplierOrIsCustomer");
        codes.add("isDelete");
        // 获取机会状态字典
        String stateDictCode = "approvalStatus";
        List<String> dictCodes = new ArrayList<>();
        dictCodes.add(stateDictCode);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", dictCodes);
        LinkedHashMap linkedHashMap = (LinkedHashMap) jsonObject.get("result");
        List<Map> approvalStatus = (List) linkedHashMap.get("approvalStatus");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < cusotmerList.size(); i++) {
            CustomerVO customerVO = cusotmerList.get(i);
            customerVO.setCustomerId(i+1);
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("rank_correlation")) {
                if(dictionaryLookupItemVO.getItemCode().equals(customerVO.getRankCorrelation()+"")){
                    customerVO.setRankCorrelationStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            for (Map item:approvalStatus) {
                if(item.get("itemCode").equals(customerVO.getStatus()+"")){
                    customerVO.setStatusStr((String) item.get("itemName"));
                    break;
                }
            }
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("isSupplierOrIsCustomer")) {
                if(dictionaryLookupItemVO.getItemCode().equals(customerVO.getIsSupplier()+"")){
                    customerVO.setIsSupplierStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("isDelete")) {
                if(dictionaryLookupItemVO.getItemCode().equals(customerVO.getIsDelete()+"")){
                    customerVO.setIsDeleteStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String productTemplatePath = String.valueOf(properties.get("report.customerTemplate"));

        //依据根目录获取模板位置
        ExportParams exportParams = new ExportParams();
        ReportUtils.exportNoTempExcel(exportParams,CustomerVO.class,cusotmerList,response);
    }

    @Override
    public Map<String, Object> queryTodoCustomerByApprovalId(Integer approvalId) {
        HashMap<String,Object> res = new HashMap<>();
        res.put("products",customerMapper.queryTodoCustomerByApprovalId(approvalId));
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    @Override
    public Map<String, Object> queryHistoryCustomerByApprovalId(Integer approvalId) {
        HashMap<String,Object> res = new HashMap<>();
        List<CustomerVO> customerVOS = customerMapper.queryHistoryCustomerByApprovalId(approvalId);
        if(customerVOS.size()>=1){
            for (CustomerVO customerVO : customerVOS) {
                List<ContactsVO> contactsVOS = customerMapper.selectBackContactsByCustomerID(customerVO);
                customerVO.setContacts(contactsVOS);
            }
            res.put("products",customerVOS);
        }else {
            res.put("products",customerMapper.queryTodoCustomerByApprovalId(approvalId));
        }
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    public void sendEmailAndPushNotice(SysUserEntity users,CustomerVO customer,String token){
        CustomerVO vo = customerMapper.selectCustomerById(customer.getCustomerId());
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(),  new Timestamp(System.currentTimeMillis()), vo.getCreator(),
                Constants.WORK_STATE_START,Constants.CUSTOMER_TASK_TYPE,users.getUserId(),token));
    }

    public void apSendEmailAndPushNotice(CustomerVO customer,String token){
        CustomerVO vo = customerMapper.selectCustomerById(customer.getCustomerId());
        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
            vo.setAuditOpinion("无");
        }
        //获取人员信息
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(customer.getCreator(),token);
        SysUserEntity user = res.getResult();
        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(customer.getEnterpriseId());
        //发送邮件
        String titel = "【系统通知】客户信息 - 流程单审批通过通知";
        String msg = "<div>"
                + "<p> 尊敬的" + user.getLoginName() + " ：<br></p ></div>"
                + "<p> &nbsp; &nbsp; &nbsp; 您好，您提交的客户信息已通过：</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 客户名称："+enterpriseVO.getEnterpriseName() + "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 系统查看路径：客户关系管理系统 - 客户信息管理 - 客户信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=customer&me=customerInfo'>进入</a></p>"
                + "<div><p style='text-indent: 2em'>谢谢！</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
        //获取抄送
        StringBuilder emailList = selectCC(customer);
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),emailList.toString(),titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(), new Timestamp(System.currentTimeMillis()), vo.getCreator(),
                Constants.WORK_STATE_STOP,Constants.CUSTOMER_TASK_TYPE,0,token));
    }

    public void rjSendEmailAndPushNotice(CustomerVO customer,String token){
        CustomerVO vo = customerMapper.selectCustomerById(customer.getCustomerId());
        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
            vo.setAuditOpinion("无");
        }
        //获取人员信息
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(customer.getCreator(),token);
        SysUserEntity user = res.getResult();
        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(customer.getEnterpriseId());
        //发送邮件
        String titel = "【系统通知】客户信息 - 流程单审批驳回通知";
//        String msg =  "<div><p style='text-indent: 2em'>" + "尊敬的" + user.getLoginName() + "：</p></div>" +
//                "<div><p style='text-indent: 4em'>您好，您提交的客户信息已驳回：</p></div>"+
//                "<div><p style='text-indent: 4em'>客户名称："+enterpriseVO.getEnterpriseName()+"</p></div>"+
//                "<div><p style='text-indent: 4em'>驳回意见："+vo.getAuditOpinion()+"</p></div>"+
//                "<div><p style='text-indent: 4em'>说明：该邮件为系统自动发送，请勿回复。</p></div>";
        String msg = "<div>"
                + "<p> 尊敬的" + user.getLoginName() + " ：<br></p ></div>"
                + "<p> &nbsp; &nbsp; &nbsp; 您好，您提交的客户信息已被驳回：</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 客户名称："+enterpriseVO.getEnterpriseName() + "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批人："+AuthUtils.getUserName() + " / " + AuthUtils.getUserAccount() +"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批意见："+vo.getAuditOpinion()+ "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 系统查看路径：客户关系管理系统 - 客户信息管理 - 客户信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=customer&me=customerInfo'>进入</a></p>"
                + "<div><p style='text-indent: 2em'>谢谢！</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() ->  NoticUtils.pushNotic(vo.getApprovalId(), vo.getLastUpdateTime(), vo.getCreator(),
                Constants.WORK_STATE_STOP,Constants.CUSTOMER_TASK_TYPE,0,token));
    }

    //    public void rjStageSendEmailAndPushNotice(SysUserEntity users,CustomerVO customer,String token){
//        CustomerVO vo = customerMapper.selectCustomerById(customer.getCustomerId());
//        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
//            vo.setAuditOpinion("无");
//        }
//        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(customer.getEnterpriseId());
//        //发送邮件
//        String titel = "【系统通知】客户审批待处理通知";
//        String msg = "<div>"
//                + "<p> 尊敬的" + users.getLoginName() + " ：<br></p ></div>"
//                + "<p> &nbsp; &nbsp; &nbsp; 您好，您有已审批的客户信息审批已被驳回需要处理：</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 客户名称："+enterpriseVO.getEnterpriseName() + "<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 审批意见："+vo.getAuditOpinion()+ "<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                "<a href='"+webSitUrl+"/?m=crm&p=todoItems&me=todoApproval'>进入</a></p>"
//                + "<div><p style='text-indent: 2em'>谢谢！</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
//        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(users.getEmail(),null,titel,msg,token));
//        //调用通知接口
//        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(),  new Timestamp(System.currentTimeMillis()), vo.getLastUpdateBy(),
//                Constants.WORK_STATE_START,Constants.CUSTOMER_TASK_TYPE,users.getUserId(),token));
//    }
    @Resource
    TranspondEmailService transpondEmailService;

    public StringBuilder selectCC(CustomerVO customer){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("customerCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        String stringBuilder = transpondEmailService.selectTranspondEmailStr(customer.getApprovalId());
        if (stringBuilder.length() > 0 && emailList.length() > 0){
            emailList.append(",");
            emailList.append(stringBuilder);
        }
        if (stringBuilder.length() > 0 && emailList.length() == 0){
            emailList.append(stringBuilder);
        }
        return emailList;
    }


    @Resource
    private SalesProjectManageMapper salesProjectManageMapper;

    @Resource
    private SalesOpportunityMapper salesOpportunityMapper;


    @Resource
    private ReimburseService reimburseService;

    @Resource
    private SalesProjectManageMapper projectManageMapper;

    @Resource
    private BrAndBmrMapper brAndBmrMapper;

    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private BrAndBmrService brAndBmrService;
    /**
     * 依据客户ID获取客户相关信息
     * @param customerId
     * @return
     */
    @Override
    public CustomerVO queryCustomerCorrelationByCustomerID(int customerId,String token) {
        CustomerVO customerVO = new CustomerVO();
        // 获取项目相关信息
        List<SalesProjectManageVO> salesProjectManageVOS = salesProjectManageMapper.queryProjectByCustomerId(customerId);
        salesProjectManageVOS.forEach(opportunity -> opportunity.setTypeName("项目信息"));
        customerVO.getAllThings().addAll(salesProjectManageVOS);
        customerVO.setSalesProjectList(salesProjectManageVOS);

        // 获取机会信息
        List<SalesOpportunityVO> salesOpportunityVOS = salesOpportunityMapper.queryOpportunityByCustomerId(customerId);
        salesOpportunityVOS.forEach(opportunity -> opportunity.setTypeName("机会信息"));
        customerVO.getAllThings().addAll(salesOpportunityVOS);
        customerVO.setSalesOpportunityList(salesOpportunityVOS);
        // 整理当前客户名下所有的机会ID以及项目ID；
        FeeMainVO feeMainVO = new FeeMainVO();
        if (salesProjectManageVOS != null && salesProjectManageVOS.size() > 0){
            List<Integer> projectIdList = new ArrayList<>();
            for (SalesProjectManageVO item : salesProjectManageVOS) {
                projectIdList.add(item.getProjectManageId());
            }
            feeMainVO.setProjectIdList(projectIdList);
        }
        if (salesOpportunityVOS != null && salesOpportunityVOS.size() > 0){
            List<Integer> opportunityIdList = new ArrayList<>();
            for (SalesOpportunityVO item : salesOpportunityVOS) {
                opportunityIdList.add(item.getOpportunityId());
            }
            feeMainVO.setChanceIdList(opportunityIdList);
        }
        //获取报销信息
        if ((feeMainVO.getProjectIdList() != null && feeMainVO.getProjectIdList().size() > 0) || (feeMainVO.getChanceIdList() != null && feeMainVO.getChanceIdList().size() > 0)){
            List<FeeMainVO> feeMainVOS = (List<FeeMainVO>) reimburseService.queryReimburseListByProjectIdListOrChanceIdList(feeMainVO,token).getResult();
            customerVO.getAllThings().addAll(feeMainVOS);
            customerVO.setFeeMainList(feeMainVOS);
        }
        // 获取回款计划
        List<ContractInfoVO> bmpList = projectManageMapper.getProjectAllBackmoneyPlanByProjectList(customerId);
        customerVO.setBmpList(bmpList);
        for (ContractInfoVO contractInfoVO : bmpList) {
            if (contractInfoVO.getBackMoneyPlanList().size() >0){
                for (BackMoneyPlanVo backMoneyPlanVo : contractInfoVO.getBackMoneyPlanList()) {
                    HashMap<String, Object> hashMap = new HashMap<>();
                    hashMap.put("bmpId",backMoneyPlanVo.getBmpId());
                    hashMap.put("creator",backMoneyPlanVo.getCreator());
                    hashMap.put("createDataTime",backMoneyPlanVo.getCreateDataTime());
                    hashMap.put("contractTopic",contractInfoVO.getContractTopic());
                    hashMap.put("bmpPeriod",backMoneyPlanVo.getBmpPeriod());
                    hashMap.put("bmpDate",backMoneyPlanVo.getBmpDate());
                    hashMap.put("bmpMoney",backMoneyPlanVo.getBmpMoney());
                    hashMap.put("flushMoney",backMoneyPlanVo.getFlushMoney());
                    hashMap.put("liableId",backMoneyPlanVo.getLiableId());
                    hashMap.put("bmpRemarks",backMoneyPlanVo.getBmpRemarks());

                    //合同甲方
                    hashMap.put("contractLessorId",contractInfoVO.getContractLessorId());
                    Map<String, String> allPageShowMoney= brAndBmrService.getAllPageShowMoneybyBmpId(backMoneyPlanVo.getBmpId());
                    hashMap.put("allPageShowMoney",allPageShowMoney);
                    hashMap.put("approvalStatus",contractInfoVO.getApprovalStatus());
                    customerVO.getAllThings().add(hashMap);
                }
            }
        }
        // 获取回款记录
        List<ContractInfoVO> bmrList = brAndBmrMapper.getProjectAllBackMoneyRecordByprojectIdList(customerId);
        for (ContractInfoVO contractInfoVO : bmrList) {
            if (contractInfoVO.getBackMoneyRecordVoList().size() > 0){
                for (BackMoneyRecordVo backMoneyRecordVo : contractInfoVO.getBackMoneyRecordVoList()) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("contractLessorId",contractInfoVO.getContractLessorId());
                    map.put("contractTopic",contractInfoVO.getContractTopic());
                    backMoneyRecordVo.setAllInfo(map);
                    customerVO.getAllThings().add(backMoneyRecordVo);
                }
            }
        }
        // 获取未回款项
        List<ContractInfoVO> notBmr = contractInfoMapper.queryContractInfoByProjectList(customerId);
        notBmr.forEach(opportunity -> opportunity.setTypeName("未回款项"));
        customerVO.setNotBmrList(notBmr);
        customerVO.getAllThings().addAll(notBmr);
        return customerVO;
    }

    @Override
    public Boolean transferCustomer(Integer userId, List<CustomerVO> customer) {
        // 日志记录
        customerMapper.backCustomerListData(customer);
        return customerMapper.updatePessorId(userId,customer);
    }

    /**
     * 通过客户ID查询客户视图信息接口
     * @param customerId
     * @param token
     * @return
     */
    @Override
    public CustomerVO getCustomerDocumentaryViewInfo(Integer customerId,String token) {
        CustomerVO customerDocumentaryViewInfo = customerMapper.getCustomerDocumentaryViewInfo(customerId);
        List<ContactsVO> contactsInfo = customerMapper.queryAllContacts();

        List<ContactsVO> con = new ArrayList<>();
        for (int j = 0; j < contactsInfo.size(); j++) {
            if (customerDocumentaryViewInfo.getCustomerId().equals(contactsInfo.get(j).getCustomerId())) {
                con.add(contactsInfo.get(j));
            }
        }
        if (null != con && con.size() != 0) {
            customerDocumentaryViewInfo.setContacts(con);
        }

        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("rank_correlation");
        Map<String, List<DictionaryLookupItemVO>> dataDictionaryLookupItems = dictionaryService.queryDictionaryLookupInfo(null,classfiedCode);
        List<DictionaryLookupItemVO> rankCorrelation = dataDictionaryLookupItems.get("rank_correlation");
        for (DictionaryLookupItemVO item : rankCorrelation) {
            if (item.getItemCode().equals(customerDocumentaryViewInfo.getRankCorrelation().toString())){
                customerDocumentaryViewInfo.setRankCorrelationName(item.getItemName());
            }
        }
        List<SysUserEntity> userList = feginService.getUserIgnoreFlag(token).getResult();
        for (SysUserEntity sysUserEntity : userList) {
            if (sysUserEntity.getUserId().equals(customerDocumentaryViewInfo.getPossessor())){
                customerDocumentaryViewInfo.setPossessorName(sysUserEntity.getLoginName() + " / " + sysUserEntity.getAccount());
            }
        }
        return customerDocumentaryViewInfo;
    }
}
